package com.study.controller.user;

import com.study.constant.JwtClaimsConstant;
import com.study.dto.UserLoginDTO;
import com.study.entity.User;
import com.study.properties.JwtProperties;
import com.study.result.Result;
import com.study.service.UserService;
import com.study.utils.JwtUtil;
import com.study.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;

    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "微信登录")
    public Result<UserLoginVO> wxLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录参数：{}", userLoginDTO);
        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 根据id返回用户详细信息
     * @param userId
     * @return
     */
    @GetMapping("/detail/{userId}")
    @ApiOperation(value = "根据id返回用户详细信息")
    public Result<User> detail(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public Result updateUser(@RequestBody User user) {
        log.info("更新用户信息：{}", user);
        userService.updateUser(user);
        return Result.success();
    }
}
